﻿using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing.Printing;
using System.Xml.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

using static System.Net.Mime.MediaTypeNames;
using System.Drawing.Imaging;

namespace Tecarrier.Tools
{
    public static class PhotoToPDFHelper
    {
        public static ConvertResult GeneratePdfFile(string photoFolder, string pdfPath, double compressionRatio)
        {
            List<string> imageFiles = new List<string>();
            try
            {
                var allFiles = Directory.GetFiles(photoFolder, "*.*");

                foreach (var file in allFiles)
                {
                    if (IsImageFile(file))
                    {
                        imageFiles.Add(file);
                    }
                }

                if (imageFiles.Count > 0)
                {
                    Document document = new Document(PageSize.A4, 0, 0, 0, 0);
                    FileStream output = new FileStream(pdfPath, FileMode.Create);
                    PdfWriter writer = PdfWriter.GetInstance(document, output);
                    document.Open();

                    if (imageFiles.Any())
                    {
                        foreach (var imageFile in imageFiles)
                        {
                            Bitmap tmpImg = new Bitmap(imageFile);

                            // 获取PDF页面大小
                            iTextSharp.text.Rectangle pageSize = document.PageSize;

                            // 按比例缩放后的新图片
                            var newImg = PercentImage(tmpImg, compressionRatio);
                            if(newImg != null)
                            {
                                // 计算图像缩放比例
                                float widthRatio = pageSize.Width / newImg.Width;
                                float heightRatio = pageSize.Height / newImg.Height;
                                float ratio = Math.Min(widthRatio, heightRatio);

                                // 计算图像在PDF中的宽度和高度
                                float width = newImg.Width * ratio;
                                float height = newImg.Height * ratio;

                                // 创建一个新的PDF页面，并设置图像在页面中的位置
                                document.SetPageSize(new iTextSharp.text.Rectangle(pageSize.Width, height));
                                document.NewPage();
                                iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(newImg, ImageFormat.Jpeg);
                                pdfImage.ScaleAbsolute(pageSize.Width, height);
                                pdfImage.SetAbsolutePosition(0, 0);
                                //pdfImage.SetDpi(72, 72);

                                document.Add(pdfImage);
                            }
                            else
                            {
                                document.Close();
                                return ConvertResult.Failed;
                            }
                        }
                    }
                    document.Close();
                    return ConvertResult.Success;
                }
                else
                {
                    return ConvertResult.NoPhotoes;
                }
            }
            catch (Exception)
            {

                return ConvertResult.Failed;
            }
        }

        public static bool IsImageFile(string fileName)
        {
            string strFilter = ".jpeg|.gif|.jpg|.png|.bmp|.pic|.tiff|.ico|.iff|.lbm|.mag|.mac|.mpt|.opt|";
            char[] separtor = { '|' };
            string[] tempFileds = StringSplit(strFilter, separtor);
            foreach (string str in tempFileds)
            {
                if (str.ToUpper() == fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")).ToUpper()) { return true; }
            }
            return false;
        }

        // 通过字符串，分隔符返回string[]数组 
        public static string[] StringSplit(string s, char[] separtor)
        {
            string[] tempFileds = s.Trim().Split(separtor); return tempFileds;
        }

        public static Bitmap PercentImage(System.Drawing.Image srcImage, double percent)
        {
            // 缩小后的高度 
            int newH = int.Parse(Math.Round(srcImage.Height * percent).ToString());
            // 缩小后的宽度 
            int newW = int.Parse(Math.Round(srcImage.Width * percent).ToString());
            try
            {
                // 要保存到的图片 
                Bitmap b = new Bitmap(newW, newH);
                System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(b);
                // 插值算法的质量 
                g.InterpolationMode = InterpolationMode.Default;
                g.DrawImage(srcImage, new System.Drawing.Rectangle(0, 0, newW, newH), new System.Drawing.Rectangle(0, 0, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel);
                g.Dispose();
                return b;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }

    public enum ConvertResult
    {
        Success,
        Failed,
        NoPhotoes
    }
}
